﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using BMS.ViewModels;
using BMS.Models;
using BMS.Models.DataAccess;
using BMS.Utilities;
using BMS.Models.BusinessLogic;

namespace BMS.Controllers
{
    public class QuotationController : Controller
    {
        private OrderModelList oMOdelList = new OrderModelList();
        private QuotationModelConfig qModelConfig = new QuotationModelConfig();
        private OrderRepository orderRepository = new OrderRepository();
        private QuotationRepository quotationRepository = new QuotationRepository();
        private ClientRepository clientRepository = new ClientRepository();
        private FMRepository fmRepository = new FMRepository();
        private CompanyRepository companyRepository = new CompanyRepository();
        private QuotationDocument quotationDoc = new QuotationDocument();
        //
        // GET: /QuotationInvoice/

        public ActionResult Index()
        {
            ViewBag.Message = "Quotations";
            oMOdelList.orderList = orderRepository.GetAllOrders();

            return View(oMOdelList);
        }


        public ActionResult QuotCreator(String soNo, String fmName, String quotNo, DateTime orderDate, String location, String description, bool isEdited)
        {
            if (isEdited == false)
            {
                ViewBag.Message = "Create Quotation";

                qModelConfig.orderModel = orderRepository.GetOrder(soNo, fmName);
                qModelConfig.QuotationNo = fmName + "-Q-" + DateTime.Now.ToString("yyMM") + "-" + QuotationNoGenerator.GetNextQuotationNo();
                qModelConfig.QuotItemsList = new List<QuotationItemModel>();
            }
            else
            {
                ViewBag.Message = "Edit Quotation";

                qModelConfig.orderModel = orderRepository.GetOrder(soNo, fmName, quotNo);
                qModelConfig.QuotModel = quotationRepository.GetQuotation(quotNo);
                qModelConfig.QuotItemsList = quotationRepository.GetAllQuotationItems(quotNo);
                String[] tempQuotNoSplit = quotNo.Split('-');
                String[] tempQuotNoSplit2 = tempQuotNoSplit[tempQuotNoSplit.Length - 1].Split('r');
                int count = 1;
                if (tempQuotNoSplit2.Length > 1)
                    count = int.Parse(tempQuotNoSplit2[1]) + 1;

                qModelConfig.QuotationNo = fmName + "-Q-" + DateTime.Now.ToString("yyMM") + "-" + tempQuotNoSplit2[0] + "r" + count;
            }

            qModelConfig.QuotationCreateDate = DateTime.Now;
            qModelConfig.VendorNo = Configuration.VendorNo;
            qModelConfig.IsEdited = isEdited;
            qModelConfig.OldQuotationNo = quotNo;

            TempData["QModelCon"] = qModelConfig;

            return View(qModelConfig);
        }

        public ActionResult ViewQuotation(String soNo, String fmName, String quotNo)
        {
            ViewBag.Message = "Quotation Detail";
            qModelConfig.orderModel = orderRepository.GetOrder(soNo, fmName, quotNo);
            qModelConfig.QuotModel = quotationRepository.GetQuotation(quotNo);
            qModelConfig.QuotationNo = qModelConfig.QuotModel.QuotationNo;
            qModelConfig.QuotationCreateDate = qModelConfig.QuotModel.QuotationCreationDate;
            qModelConfig.VendorNo = Configuration.VendorNo;
            qModelConfig.QuotItemsList = quotationRepository.GetAllQuotationItems(qModelConfig.QuotationNo);

            return View(qModelConfig);
        }

        [HttpPost]
        public ActionResult Switch(String command)
        {

            if (command == "Save")
            {
                SaveQuotation();
                return RedirectToAction("Index");
            }
            else if (command == "Close")
                return RedirectToAction("Index");
            else if (command == "Cancel")
                return RedirectToAction("Index");

            return View();
        }

        [HttpPost]
        public ActionResult SaveQuotation()
        {
            if (TempData["QModelCon"] != null)
                qModelConfig = (QuotationModelConfig)TempData["QModelCon"];

            List<QuotationItemModel> quotationItemModelList = new List<QuotationItemModel>();
            List<QuotationItemModel> quotationItemModelList2 = new List<QuotationItemModel>();
            var SONo = Request.Form["SONo"];
            var FM = Request.Form["FM"];
            var PONo = Request.Form["PONo"];
            var QuotationNo = Request.Form["QuotationNo"];
            QuotationModel tempQuotModel = new QuotationModel();
            QuotationModel tempQuotModel2 = new QuotationModel();
            OrderModel existedOrder = orderRepository.GetOrder(SONo, FM);

            var WorkOrderNo = Request.Form["WONo"];
            var VendorNo = Request.Form["VendorNo"];
            var ServiceDetail = Request.Form["ServiceDetail"];
            String[] tempDateSplit = Request.Form["QuotationCreateDate"].Split('-');
            DateTime QuotationCreationDate = new DateTime(int.Parse(tempDateSplit[0]), int.Parse(tempDateSplit[1]), int.Parse(tempDateSplit[2]));
            var TotalAmount = Request.Form["TotalAmount"];
            String[] WrkDateTimeSplit = Request.Form["WrkDate"].Split(' ');
            //String[] WrkTimeSplit = WrkDateTimeSplit[1].Split(':');
            tempDateSplit = WrkDateTimeSplit[0].Split('-');
            String tDate = tempDateSplit[0];
            DateTime? WrkCompleteionDate = null;

            if (tDate != "")
            {
                tDate = tempDateSplit[1] + " " + int.Parse(tempDateSplit[0]).ToString("00") + ", " + int.Parse(tempDateSplit[2]).ToString("0000");
                WrkCompleteionDate = DateTime.Parse(tDate);
            }

            #region Part I - Data Retrieveal
            #region Quotation Items
            for (int i = 0; i <= Request.Form.Count; i++)
            {

                if (Request.Form["ItemNo[" + i + "]"] != null)
                {
                    var ItemNo = Request.Form["ItemNo[" + i + "]"];
                    var Description = Request.Form["Description[" + i + "]"];
                    var SORItem = Request.Form["SORItem[" + i + "]"];
                    var Qty = Request.Form["Qty[" + i + "]"];
                    var Unit = Request.Form["Unit[" + i + "]"];
                    var Rate = Request.Form["Rate[" + i + "]"];
                    var Amount = Request.Form["Amount[" + i + "]"];

                    QuotationItemModel tempQuotItem = new QuotationItemModel();
                    tempQuotItem.SeqNo = i + 1;
                    tempQuotItem.QuotationNo = QuotationNo;
                    tempQuotItem.QuotationItemCreationDate = DateTime.Today;

                    //if (ExistingQuotation != null)
                    //    tempQuotItem.Location = ExistingOrder.Location;

                    if (ItemNo == "")
                        tempQuotItem.ItemNo = 0;
                    else
                        tempQuotItem.ItemNo = int.Parse(ItemNo);

                    tempQuotItem.ItemDescription = Description;
                    tempQuotItem.SORItem = SORItem;
                    if (Qty == "")
                        tempQuotItem.Qty = 0;
                    else
                        tempQuotItem.Qty = int.Parse(Qty);

                    tempQuotItem.Unit = Unit;
                    if (Rate == "")
                        tempQuotItem.Rate = 0;
                    else
                        tempQuotItem.Rate = decimal.Parse(Rate);

                    if (Amount == "")
                        tempQuotItem.ItemAmount = 0;
                    else
                        tempQuotItem.ItemAmount = decimal.Parse(Amount);

                    tempQuotItem.IsValid = "Y";

                    quotationItemModelList.Add(tempQuotItem);
                }
                else
                    break;
            }
            #endregion

            #region Quotation
            tempQuotModel.QuotationNo = QuotationNo;
            tempQuotModel.FMName = FM;
            tempQuotModel.NoOfItems = quotationItemModelList.Count;
            tempQuotModel.QuotationCreationDate = QuotationCreationDate;
            tempQuotModel.WorkCompletionDate = WrkCompleteionDate;
            tempQuotModel.HasSubContractor = "N";
            tempQuotModel.SubContName = "";
            tempQuotModel.SubContAmount = 0;
            tempQuotModel.IsValid = "Y";
            tempQuotModel.PONo = PONo;
            tempQuotModel.TotalAmount = decimal.Parse(TotalAmount);

            if (qModelConfig.IsEdited == true)
            {
                tempQuotModel2 = quotationRepository.GetQuotation(qModelConfig.OldQuotationNo);
                tempQuotModel2.IsValid = "N";

                quotationItemModelList2 = quotationRepository.GetAllQuotationItems(qModelConfig.OldQuotationNo);

                foreach(QuotationItemModel q in quotationItemModelList2)
                {
                    q.IsValid = "N";
                }
            }
            #endregion

            #region Order - Save the new Quotation No
            existedOrder.QuotationNo = QuotationNo;
            existedOrder.WorkOrderNo = WorkOrderNo;
            #endregion
            #endregion

            #region Part II - Save Data (To Database, To Word and Convert Word To PDF)
            if (quotationItemModelList.Count > 0)
            {
                #region Part IIa - To Database
                // (a) Save a new record in Quotation
                quotationRepository.Insert(tempQuotModel);

                // (b) Save a list of quotation items
                quotationRepository.Insert(quotationItemModelList);

                if (qModelConfig.IsEdited == true)
                {
                    quotationRepository.UpdateInValidFlag(tempQuotModel2);
                    quotationRepository.UpdateInValidFlag(quotationItemModelList2);
                }

                // (c) Update Work Service No & Quotation No in Order
                orderRepository.Update(existedOrder);
                #endregion

                #region Part IIb - To Word
                FMModel fm = fmRepository.GetFM(tempQuotModel.FMName);
                CompanyModel company = new CompanyModel();

                if (fm != null)
                    company = companyRepository.GetCompany(fm.CompanyName);

                quotationDoc.GenerateQuotation(tempQuotModel, quotationItemModelList, fm, company, existedOrder);
                #endregion

                //#region Part IIb - To PDF
                //// (c) Save the quotation records into a PDF File
                //PDF_QuotationInvoiceModel pdfQuotation = new PDF_QuotationInvoiceModel();
                //pdfQuotation.QuotationItemsList = quotationItemModelList;
                //pdfQuotation.IsQuotation = true;
                //pdfQuotation.IsInvoice = false;
                //pdfQuotation.QuotationNo = tempQuotModel.QuotationNo;
                //pdfQuotation.QuotationDate = tempQuotModel.QuotationCreationDate;
                //pdfQuotation.WorkOrderNo = existedOrder.WorkOrderNo;
                //pdfQuotation.PONo = tempQuotModel.PONo;
                //pdfQuotation.ReferenceNo = "";
                //pdfQuotation.VendorNo = Configuration.VendorNo;
                //pdfQuotation.WorkCompletionDate = tempQuotModel.WorkCompletionDate;
                //pdfQuotation.Location = existedOrder.Location;
                //pdfQuotation.ServiceDetail = existedOrder.Description;
                //pdfQuotation.PDFDestPath += @"Quotation\" + pdfQuotation.QuotationNo + @"\";
                //pdfQuotation.SetPDfFileName();
                //pdfQuotation.client = clientRepository.GetClient(existedOrder.FMName);

                //if (Directory.Exists(pdfQuotation.PDFDestPath) == false)
                //    Directory.CreateDirectory(pdfQuotation.PDFDestPath);

                //PDFUtil.PDFCreation(pdfQuotation.PDFDestPath, pdfQuotation.PDFFileName, pdfQuotation);
                //#endregion

                //#region Part IIc - To Excel
                //ExcelModel excelQuotation = new ExcelModel();
                //excelQuotation.Data = pdfQuotation;
                //excelQuotation.ExcelDestPath += @"Quotation\" + excelQuotation.Data.QuotationNo + @"\";
                //excelQuotation.ExcelFileName = pdfQuotation.QuotationNo + ".xlsx";

                //if (Directory.Exists(excelQuotation.ExcelDestPath) == false)
                //    Directory.CreateDirectory(excelQuotation.ExcelDestPath);

                //ExcelOpenXmlUtil.CreateQuotationOrInvoiceInExcelFormat("QuotNo", excelQuotation);
                //#endregion
            }
            #endregion

            return RedirectToAction("Index");
        }

    }
}
